package com.fishing.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SysUtil {
    public static String convertObjToJsonStr(Object obj) { //将Obj转化为json
    	ObjectMapper objectMapper = new ObjectMapper();  //https://www.cnblogs.com/xuwenjin/p/8976696.html
    	try {
    		return objectMapper.writeValueAsString(obj);
    	}catch (JsonProcessingException e) {
    	    e.printStackTrace();	
    	}
    	return null;
    }
    
    @SuppressWarnings("unchecked")
	public static Object convertJsonStrToObj(String jsonStr,Class targetClass) {  //公共静态方法不需要实例    
    	ObjectMapper objectMapper = new ObjectMapper();  // https://blog.csdn.net/li905663280/article/details/86560404
    	try {
    		return  objectMapper.readValue(jsonStr,targetClass);
    	}catch (IOException e) {
    		System.out.println("json转换异常");
    	}
    	return null;
    }
    
    /***
     * 基本功能:过滤所有以"<"开头 以">"结尾的标签
     * @param str
     * @return String
     * */
    public static String filterHtml(String str) {
    	Pattern pattern = Pattern.compile("<([^>])>");
    	Matcher matcher = pattern.matcher(str);
    	StringBuffer sb = new StringBuffer();
    	boolean result1 = matcher.find();
    	while(result1) {
    		matcher.appendReplacement(sb, "");
    		result1 = matcher.find();
    	}
    	matcher.appendTail(sb);
    	return sb.toString();
    }
    /***
     * 保留两位有效数字
     * @param f Double
     * @return
     * */
    public static double formatTwo(Double f) {
    	BigDecimal b = new BigDecimal(f);
    	return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /***
     * 生成六位随机数字
     * */
    public static String geneRandomSix() {
    	Random rd = new Random();
    	StringBuffer rand = new StringBuffer();
    	int num;
    	do {
			num = Math.abs(rd.nextInt()) % 10 + 48;// 产生数字0-9的随机数
			// getNum = Math.abs(rd.nextInt())%26 + 97;//产生字母a-z的随机数
			rand.append(Character.toString((char)num)) ;
		} while (rand.length() < 6);
		return rand.toString();
	}
    
    /***
     * 获取tomcat服务器的webapp目录
     * @param request HttpServletRequest
     * @return
     * */
    public static String getServerWebAppPath(HttpServletRequest request) {
		String path = request.getSession().getServletContext().getRealPath("/");
		File file = new File(path);
		if(file.exists()) {
			return file.getParent();
		}
    	return path;
    }
    
    /***
     * 字符串转码UTF8
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     * */
    public static String convertToUTF8(String str) {
    	try {
    		return convertToEncode(str,"UTF-8");
    	}catch (UnsupportedEncodingException e){
    		e.printStackTrace();
    	}
    	return str;
    }
    public static String convertToEncode(String str, String encode) throws UnsupportedEncodingException{
		return new String(str.getBytes("iso-8859-1"),encode);
	}
    
    /***
     * 获取项目的web基本路径
     * @param requset HttpServletRequst
     * @return String
     * */
    public static String getBasePath(HttpServletRequest request){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
	}
    
    public static String getBaseWebappPath(HttpServletRequest request){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/";
	}
	
	public static String getNowStr(){
		return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		
	}
	
	//生成随机数字和字母
	public static String getStringRandom(int length) {
		String val = "";
		Random random = new Random();
		
		//参数length,表示生成几位随机数
		for(int i = 0; i < length; i++) {  
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
            //输出字母还是数字  
            if( "char".equalsIgnoreCase(charOrNum) ) {  
                //输出是大写字母还是小写字母  
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
                val += (char)(random.nextInt(26) + temp);  
            } else if( "num".equalsIgnoreCase(charOrNum) ) {  
                val += String.valueOf(random.nextInt(10));  
            }  
        }  
        return val;  
    }
	
	/***
	 * 从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip
	 * @param request
	 * @param ip
	 * */
	public static String getIp(HttpServletRequest request) {  //http://www.mamicode.com/info-detail-2373956.html
		String remoteAddr = request.getRemoteAddr();
	    String forwarded = request.getHeader("X-Forwarded-For");
	    String realIp = request.getHeader("X-Real-IP");
	    
	    String ip = null;
	    if(realIp == null) {
	    	if(forwarded == null) {
	    		ip = remoteAddr;
	    	}else {
	    	    ip = remoteAddr + "/" + forwarded.split(",")[0];	
	    	}
	    }else {
	    	if(realIp.equals(forwarded)) {
	    		ip = realIp;
	    	}else {
	    		if(forwarded != null) {
	    			forwarded = forwarded.split(",")[0];
	    		}
	    		ip = realIp + "/" + forwarded;
	    	}
	    }
		return ip;
	}
	
	public static String DoubleToString(Double dou_obj) {
		NumberFormat nf = NumberFormat.getInstance();   //单例模式,不创建新的对象   https://www.cnblogs.com/baxianhua/p/9341953.html
		nf.setGroupingUsed(false);   //设为false则不使用分组方式显示数据。设为true则使用分组方式显示数据，即每三位数为一个分组，分组间以英文半角逗号分隔
		return nf.format(dou_obj);
	}
	
	
}



















